package com.czmh.etc.onlinepubsys.controller.cmg;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.czmh.etc.common.core.utils.Sequence;
import com.czmh.etc.onlinepubsys.constants.cmg.BusinessType;
import com.czmh.etc.onlinepubsys.entity.mingchuang.ApplyInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CarInfo;
import com.czmh.etc.onlinepubsys.entity.mingchuang.CurrentContext;
import com.czmh.etc.onlinepubsys.entity.mingchuang.EtcOrder;
import com.czmh.etc.onlinepubsys.enums.cmg.ApiCodeEnum;
import com.czmh.etc.onlinepubsys.json.cmg.JSONResult;
import com.czmh.etc.onlinepubsys.request.cmg.*;
import com.czmh.etc.onlinepubsys.request.mingchuang.ApplyExtInfo;
import com.czmh.etc.onlinepubsys.request.mingchuang.CarInfoRequest;
import com.czmh.etc.onlinepubsys.request.mingchuang.EtcApplyReqest;
import com.czmh.etc.onlinepubsys.response.cmg.ApiResponseBase;
import com.czmh.etc.onlinepubsys.services.EtcOrderService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICarInfoService;
import com.czmh.etc.onlinepubsys.services.mingchuang.ICurrentContextService;
import com.czmh.etc.onlinepubsys.services.mingchuang.IEtcApplyService;
import com.czmh.etc.onlinepubsys.utils.cmg.CmgHttpUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/{version}/api/cmg/applyEtc")
@Api(tags = "申办卡签接口相关 - 招商局")
public class CmgDevApplyController {

    @Autowired
    private ICarInfoService carInfoService;

    @Autowired
    private IEtcApplyService etcApplyService;

    @Autowired
    private ICurrentContextService currentContextService;

    @Autowired
    private EtcOrderService etcOrderService;

    @Value("${cmg.accessno}")
    private String accessno;

    @PostMapping("/addCustomerInfo")
    @ApiOperation("录入ETC客户信息:个人用户返回用户编号，单位用户返回为空字符串")
    public JSONResult addCustomerInfo(@RequestBody EtcApplyReqest req) {
        //该接口把数据提交缓存到用户当前流程数据表
        JSONResult result = new JSONResult();
        log.info("addCustomerInfo:{}", JSON.toJSONString(req));
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        String jsonStr = currentContext.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        jsonObject.put("etcApplyRequest", req);
        currentContext.setJsonData(jsonObject.toJSONString());
        currentContextService.update(currentContext);
        return result;

/*
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ADD_CUSTOMER_INFO, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
        */
    }

    @PostMapping("/addOrUpdateBankSign")
    @ApiOperation("录入线下银行签约信息:申请成功返回签约交易流水号")
    public JSONResult addOrUpdateBankSign(@RequestBody AddOrUpdateBankSignRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表
        JSONResult result = new JSONResult();
        log.info("addOrUpdateBankSign:{}", JSON.toJSONString(req));
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        String jsonStr = currentContext.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        jsonObject.put("addOrUpdateBankSignRequest", req);
        currentContext.setJsonData(jsonObject.toJSONString());
        currentContextService.update(currentContext);
        return result;


/*        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        req.setSignChannelId(accessno + time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ADD_OR_UPDATE_BANK_SIGN, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;*/
    }

    @PostMapping("/addVehicle")
    @ApiOperation("车辆信息录入")
    public JSONResult addVehicle(@RequestBody CarInfoRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表
        JSONResult result = new JSONResult();
        log.info("addVehicle:{}", JSON.toJSONString(req));
        CurrentContext currentContext = currentContextService.getByUserId(req.getVehicle().getUserId());
        String jsonStr = currentContext.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        jsonObject.put("carInfoRequest", req);
        currentContext.setJsonData(jsonObject.toJSONString());
        currentContextService.update(currentContext);
        return result;
/*
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ADD_VEHICLE, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                //车辆信息入库


            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
        */
    }

    @PostMapping("/addAgent")
    @ApiOperation("录入经办人信息:单位用户返回经办人编码")
    public JSONResult addAgent(@RequestBody AddAgentRequest req) {
        //该接口把数据提交缓存到用户当前流程数据表
        JSONResult result = new JSONResult();
        log.info("addAgent:{}", JSON.toJSONString(req));
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        String jsonStr = currentContext.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonStr);
        if (jsonObject == null) {
            jsonObject = new JSONObject();
        }
        jsonObject.put("addAgentRequest", req);
        currentContext.setJsonData(jsonObject.toJSONString());
        currentContextService.update(currentContext);
        return result;

/*
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ADD_AGENT, req);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
        */
    }

    @PostMapping("/applyInfo")
    @ApiOperation("申请信息提交")
    public JSONResult applyInfo(@RequestBody CmgApplyInfoRequest req) {
        //该接口之前缓存的数据按照申请流程接口逐个提交，对于已经提交过的数据则调用对应的更新接口而不是调用新增接口
        JSONResult result = new JSONResult();
        CmgApplyInfoRequest request = JSON.parseObject(JSON.toJSONString(req), CmgApplyInfoRequest.class);
        request.getCarInfoRequest().setVehCertBackImg("");
        request.getCarInfoRequest().setVehCertFrontImg("");
        request.getEtcApplyRequest().setAgentBackImg("");
        request.getEtcApplyRequest().setAgentFrontImg("");
        request.getEtcApplyRequest().setCertImg("");
        log.info("applyInfo:{}", JSON.toJSONString(request));
        //申请信息JSON对象
        JSONObject etcApplyRequest = null;
        //获取接口对应的各个请求对象
        //车辆信息
        CarInfo carInfo = req.getCarInfoRequest().getVehicle();
        //经办人信息
        AddAgentRequest agentRequest = req.getAddAgentRequest();
        //银行签约信息
        AddOrUpdateBankSignRequest addOrUpdateBankSignRequest = req.getAddOrUpdateBankSignRequest();
        //etc申请信息
        EtcApplyReqest etcApplyReqest = req.getEtcApplyRequest();
        CarInfoRequest carInfoRequest = req.getCarInfoRequest();
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("该用户不在申办流程当中！");
        }
        //获取用户申请信息和车辆信息为下面的接口提交做准备
        String jsonData = currentContext.getJsonData();
        JSONObject jsonObject = JSON.parseObject(jsonData);
        String etcApplyRequestStr = jsonObject.getString("etcApplyRequest");
        etcApplyRequest = JSON.parseObject(etcApplyRequestStr);
        ApplyInfo applyInfo = etcApplyService.get(currentContext.getApplyId());
        CarInfo etcCarInfo = carInfoService.get(currentContext.getCarId());


        //1、完成ETC客户信息提交
        if (etcApplyReqest != null) {
            AddCustomerInfoRequest addCustomerInfoRequest = AddCustomerInfoRequest.translate(etcApplyReqest);
            String orderNo = currentContext.getOrderNo();
            EtcOrder etcOrder = etcOrderService.queryByOrderNo(orderNo);
            etcOrder.setAddress(etcApplyReqest.getAddress());
            etcOrder.setVehPlate(etcOrder.getVehPlate());
            etcOrder.setVehColor(etcOrder.getVehColor());
            etcOrderService.updateById(etcOrder);
            addCustomerInfoRequest.setTel(etcOrder.getPhone());
            req.getEtcApplyRequest().setMobile(etcOrder.getPhone());
            Long time = System.currentTimeMillis();
            addCustomerInfoRequest.setClientKey(accessno + time);
            addCustomerInfoRequest.setTime(time);
            //判断办理用户类型是个人还是企业
            if (addCustomerInfoRequest.getUserProperties().intValue() == 0) {
                addCustomerInfoRequest.setUserProperties(1);
                addCustomerInfoRequest.setPicData(etcApplyReqest.getAgentFrontImg());
                addCustomerInfoRequest.setPicData2(etcApplyReqest.getAgentBackImg());
            } else {
                addCustomerInfoRequest.setUserProperties(6);
                addCustomerInfoRequest.setPicData(etcApplyReqest.getCertImg());
                addCustomerInfoRequest.setPicData2("");
            }
//            ApiResponseBase r = null;
//            r = CmgHttpUtil.post(BusinessType.ADD_CUSTOMER_INFO, addCustomerInfoRequest);
            //判断用户是否提交过ETC客户信息，是的话则调用更新接口，否则调用新增接口
/*            if(StringUtils.isEmpty(currentContext.getCsUserNo())){
                r = CmgHttpUtil.post(BusinessType.ADD_CUSTOMER_INFO, addCustomerInfoRequest);
            }else{
                UpdateCustomerInfoRequest updateCustomerInfoRequest = new UpdateCustomerInfoRequest();
                BeanUtil.copyProperties(addCustomerInfoRequest, updateCustomerInfoRequest);
                updateCustomerInfoRequest.setOldIdNum(applyInfo.getCertifiNo());
                updateCustomerInfoRequest.setOldIdType(applyInfo.getCertifiType());
                updateCustomerInfoRequest.setTel(etcApplyRequest.getString("mobile"));
                updateCustomerInfoRequest.setClientKey(accessno + time);
                updateCustomerInfoRequest.setTime(time);
                r = CmgHttpUtil.post(BusinessType.UPDATE_CUSTOMER_INFO, updateCustomerInfoRequest);
            }*/
//            if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
//                if(r.bizContent != null){
//                    carInfo.setCsUserNo(r.getBizContent());
            carInfoRequest.setVehicle(carInfo);
            //申请用户信息入库并把用户申请状态设置成2
            //处理用户上传的图片信息
            ApplyExtInfo applyExtInfo = req.getEtcApplyRequest().getApplyExtInfo();
            //按照用户请求流程的申请ID判断更新用户申请信息还是新增用户申请信息
            if (StringUtils.isNotEmpty(currentContext.getApplyId())) {
                if (null != applyInfo) {
                    ApplyInfo applyInfo1 = new ApplyInfo(null, req.getUserId(), "", etcApplyReqest.getAccountName(),
                            etcApplyReqest.getOwnerType(), etcApplyReqest.getCertifiType(), etcApplyReqest.getCertifiNo(), etcApplyReqest.getAgentIdNum(), addCustomerInfoRequest.getTel(), etcApplyReqest.getDepartment(),
                            etcApplyRequest.getString("agentFrontImg"), etcApplyRequest.getString("agentBackImg"), etcApplyRequest.getString("certImg"), etcApplyReqest.getEnterpriseName(),
                            etcApplyReqest.getEnterpriseNo(), null, null, null, null,
                            null, currentContext.getOrderNo(), null, null, 0, null, 0, applyExtInfo == null ? null : JSON.toJSONString(applyExtInfo));
                    applyInfo1.setId(applyInfo.getId());
                    etcApplyService.update(applyInfo1);
                    currentContext.setApplyId(applyInfo.getId());
                } else {
                    log.info("applyInfo is null");
                }
            } else {
                ApplyInfo applyInfo1 = new ApplyInfo(Sequence.getId(), req.getUserId(), "", etcApplyReqest.getAccountName(),
                        etcApplyReqest.getOwnerType(), etcApplyReqest.getCertifiType(), etcApplyReqest.getCertifiNo(), etcApplyReqest.getAgentIdNum(), addCustomerInfoRequest.getTel(), etcApplyReqest.getDepartment(),
                        etcApplyRequest.getString("agentFrontImg"), etcApplyRequest.getString("agentBackImg"), etcApplyRequest.getString("certImg"), etcApplyReqest.getEnterpriseName(),
                        etcApplyReqest.getEnterpriseNo(), null, null, null, null,
                        null, currentContext.getOrderNo(), null, null, 0, null, 0, applyExtInfo == null ? null : JSON.toJSONString(applyExtInfo));
                etcApplyService.save(applyInfo1);
                applyInfo = applyInfo1;
                currentContext.setApplyId(applyInfo1.getId());
            }
            //更新申请流程状态
//                    currentContext.setCsUserNo(r.getBizContent());
            if (currentContext.getState() > 2) {
            } else {
                currentContext.setState(2); //已提交申请
            }
            currentContextService.update(currentContext);
        }
//            }else{
//                result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
//                result.setMessage(r.getMsg());
//                result.setCurrentTime(r.getReceiveTime());
//                return result;
//            }
//        }else{
//            result.setCode(JSONResult.FAIL);
//            result.setMessage("ETC客户信息缺失");
//            result.setCurrentTime("" + System.currentTimeMillis());
//            return result;
//        }

        //2、完成经办人信息提交-先判断车辆信息当中的csUserNo是否为空和车辆经办人信息是否为空
        if (agentRequest != null) {
            etcApplyRequest.put("agentFrontImg", agentRequest.getAgentFrontImgUrl());
            etcApplyRequest.put("agentBackImg", agentRequest.getAgentBackImgUrl());
            if (currentContext.getCsUserNo().equalsIgnoreCase("null")) {
                Long time = System.currentTimeMillis();
                agentRequest.setClientKey(accessno + time);
                agentRequest.setTime(time);
                agentRequest.setIdNum(etcApplyReqest.getCertifiNo());
                agentRequest.setIdType(etcApplyReqest.getCertifiType());
                agentRequest.setDepartment(etcApplyReqest.getDepartment());
//                ApiResponseBase r = CmgHttpUtil.post(BusinessType.ADD_AGENT, agentRequest);
//                if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
//                    if(r.bizContent != null){
                //经办人信息录入之后同步把用户csUserNo信息入库
//                        carInfo.setCsUserNo(r.getBizContent() != null ? r.getBizContent() : "");
                carInfoRequest.setVehicle(carInfo);
//                        currentContext.setCsUserNo(r.getBizContent());
                currentContextService.update(currentContext);
                ApplyInfo applyInfo1 = etcApplyService.get(currentContext.getApplyId());
//                        applyInfo1.setCsUserNo(r.getBizContent());
                applyInfo1.setAgentIdNum(agentRequest.getAgentIdNum());
                etcApplyService.update(applyInfo1);
            }
//                }else {
//                    result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
//                    result.setMessage(r.getMsg());
//                    result.setCurrentTime(r.getReceiveTime());
//                    return result;
//                }
//            }
        }

//        if (currentContext.getState().intValue() < 3) {
//            //用户信息录入之后要先进行车辆卡签校验查询，然后才进行车辆信息录入
//            Long t = System.currentTimeMillis();
//            CheckAndQueryVehilceRequest checkAndQueryVehilceRequest = new CheckAndQueryVehilceRequest();
//            checkAndQueryVehilceRequest.setClientKey(accessno + t);
//            checkAndQueryVehilceRequest.setTime(t);
//            checkAndQueryVehilceRequest.setIdType(applyInfo.getCertifiType());
//            checkAndQueryVehilceRequest.setIdNum(applyInfo.getCertifiNo());
//            checkAndQueryVehilceRequest.setVehiclePlate(req.getCarInfoRequest().getVehicle().getVehPlate());
//            checkAndQueryVehilceRequest.setVehiclePlateColor(req.getCarInfoRequest().getVehicle().getVehColor());
//            ApiResponseBase responseBase = CmgHttpUtil.newpost(BusinessType.NEW_CHECK_AND_QUERY_VEHILCE, checkAndQueryVehilceRequest);
//            if (responseBase != null && (responseBase.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode()) || responseBase.getCode().equalsIgnoreCase("1010"))) {
//                //车辆信息不存在时引导用户完成新增车辆信息
//                if (responseBase.getCode().equalsIgnoreCase("1010")) {
//                    currentContext.setCarId("");
//                }
//            } else {
//                result.setCode(responseBase != null ? responseBase.getCode() : JSONResult.FAIL);
//                result.setMessage(responseBase.getMsg());
//                result.setCurrentTime(responseBase.getReceiveTime());
//                return result;
//            }
//        }

        //3、完成ETC车辆信息提交
        if (carInfoRequest != null) {
//            AddVehicleRequest addVehicleRequest = AddVehicleRequest.translate(carInfoRequest.getVehicle());
//            addVehicleRequest.setDepartment(etcApplyReqest.getDepartment());
//            addVehicleRequest.setIdType(etcApplyReqest.getCertifiType());
//            addVehicleRequest.setPicData(carInfoRequest.getVehCertFrontImg());
//            addVehicleRequest.setPicData2(carInfoRequest.getVehCertBackImg());
//            Long time = System.currentTimeMillis();
//            addVehicleRequest.setClientKey(accessno + time);
//            addVehicleRequest.setTime(time);
//            addVehicleRequest.setIdNum(req.getEtcApplyRequest().getCertifiNo());
            //增加座位数参数判断
//            if (addVehicleRequest.getVehicleWeightLimits() == null) {
//                result.setCode(JSONResult.FAIL);
//                result.setMessage("请填写座位数！");
//                result.setCurrentTime("" + System.currentTimeMillis());
//                return result;
//            }
//            ApiResponseBase r = null;
            //根据流程汽车信息id判断是调用ETC车辆信息新增接口还是更新接口
//            log.info("currentContext-{}", JSON.toJSONString(currentContext));
//            if (StringUtils.isEmpty(currentContext.getCarId())){
//                r = CmgHttpUtil.post(BusinessType.ADD_VEHICLE, addVehicleRequest);
//            }else{
//                UpdateVehicleRequest updateVehicleRequest = new UpdateVehicleRequest();
//                BeanUtil.copyProperties(addVehicleRequest, updateVehicleRequest);
//                updateVehicleRequest.setCsUserNo(currentContext.getCsUserNo());
//                updateVehicleRequest.setOldVehiclePlate(etcCarInfo.getVehPlate());
//                updateVehicleRequest.setOldVehiclePlateColor(etcCarInfo.getVehColor());
//                updateVehicleRequest.setClientKey(accessno + time);
//                updateVehicleRequest.setTime(time);
//                r = CmgHttpUtil.post(BusinessType.UPDATE_VEHICLE, updateVehicleRequest);
//            }

//            if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
//                if(r.bizContent != null){
            //完成ETC车辆信息提交之后再更新一次车辆信息
            carInfoRequest.setVehicle(carInfo);
            CarInfo vehicle = carInfoRequest.getVehicle();
            String vehPlate = vehicle.getVehPlate();
            //根据流程汽车信息id判断是调用ETC车辆信息新增入库还是更新入库
            if (StringUtils.isEmpty(currentContext.getCarId())) {
                vehicle.setId(Sequence.getId());
                vehicle.setOwnerTel(req.getEtcApplyRequest().getMobile());
                vehicle.setUserId(req.getUserId());
                vehicle.setAxleCount(2);
                vehicle.setWheelCount(4);
                carInfoService.save(vehicle);
            } else {
                etcCarInfo.setOwnerTel(req.getEtcApplyRequest().getMobile());
                etcCarInfo.setUserId(req.getUserId());
                etcCarInfo.setAxleCount(2);
                etcCarInfo.setWheelCount(4);
                carInfoService.update(etcCarInfo);
            }
            //处理用户上传的图片信息
            if (StringUtils.isNotEmpty(applyInfo.getJsonData())) {
                ApplyExtInfo applyExtInfo = JSON.parseObject(applyInfo.getJsonData(), ApplyExtInfo.class);
                applyExtInfo.setVehCertBackImgUrl(carInfoRequest.getApplyExtInfo().getVehCertBackImgUrl());
                applyExtInfo.setVehCertFrontImgUrl(carInfoRequest.getApplyExtInfo().getVehCertFrontImgUrl());
                applyInfo.setJsonData(JSON.toJSONString(applyExtInfo));
            }
            //更新车辆申请相关车辆信息
            applyInfo.setVehCertFrontImg(carInfoRequest.getApplyExtInfo().getVehCertFrontImgUrl());
            applyInfo.setVehCertbackImg(carInfoRequest.getApplyExtInfo().getVehCertBackImgUrl());
            applyInfo.setVehiclePlate(vehPlate);
            applyInfo.setVehicleColor(vehicle.getVehColor());
            applyInfo.setVehicleType(carInfoRequest.getVehicle().getType());
            etcApplyService.update(applyInfo);

            //更新申请流程状态
            currentContext.setCarId(vehicle.getId());
            currentContext.setState(3); //已添加车辆信息
            currentContextService.update(currentContext);
        }
//            }else{
//                result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
//                result.setMessage(r.getMsg());
//                result.setCurrentTime(r.getReceiveTime());
//                return result;
//            }
//        }else{
//            result.setCode(JSONResult.FAIL);
//            result.setMessage("ETC车辆信息缺失");
//            result.setCurrentTime("" + System.currentTimeMillis());
//            return result;
//        }

        //4、录入线下银行签约信息-因为该接口可以满足新增和更新所以不需要对该接口进行状态的判断和相关处理
        //线上签约不需要录入线下银行签约信息
/*        if(addOrUpdateBankSignRequest != null && req.getSignType() != null && req.getSignType().intValue() == 1){
            Long time = System.currentTimeMillis();
            addOrUpdateBankSignRequest.setClientKey(accessno + time);
            addOrUpdateBankSignRequest.setTime(time);
            addOrUpdateBankSignRequest.setSignChannelId(accessno + System.currentTimeMillis());
            addOrUpdateBankSignRequest.setVehiclePlate(carInfoRequest.getVehicle().getVehPlate());
            addOrUpdateBankSignRequest.setVehiclePlateColor(carInfoRequest.getVehicle().getVehColor());
            ApiResponseBase r = CmgHttpUtil.post(BusinessType.ADD_OR_UPDATE_BANK_SIGN, addOrUpdateBankSignRequest);
            if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
                if(r.bizContent != null){
                    CurrentContext ctx = currentContextService.getByUserId(req.getUserId());
                    ctx.setTransNo(r.getBizContent());
                    ctx.setState(3);
                    ctx.setSignChannelId(addOrUpdateBankSignRequest.getSignChannelId());
                    currentContextService.update(ctx);
                    applyInfo.setBankSignTime(new Date());
                    applyInfo.setState(1);
                    applyInfo.setBankCardNo(addOrUpdateBankSignRequest.getBankCardNo());
                    applyInfo.setBankSn(addOrUpdateBankSignRequest.getBankCode());
                    applyInfo.setBankCardType(addOrUpdateBankSignRequest.getBankCardType());
                    etcApplyService.update(applyInfo);
                }
            }else{
                result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
                return result;
            }
        }*/

/*        //5、申办订单提交
        SubmitBusinessRequest submitBusinessRequest = new SubmitBusinessRequest();
        submitBusinessRequest.setCsUserNo(currentContext.getCsUserNo());
        submitBusinessRequest.setIdNum(etcApplyReqest.getCertifiNo());
        submitBusinessRequest.setIdType(etcApplyReqest.getCertifiType());
        submitBusinessRequest.setOrderNo(accessno + currentContext.getOrderNo());
        submitBusinessRequest.setVehiclePlate(carInfoRequest.getVehicle().getVehPlate());
        submitBusinessRequest.setVehiclePlateColor(carInfoRequest.getVehicle().getVehColor());
        Long time = System.currentTimeMillis();
        submitBusinessRequest.setClientKey(accessno + time);
        submitBusinessRequest.setTime(time);
        log.info("submitBusiness:{}", JSON.toJSONString(submitBusinessRequest));
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.SUBMIT_BUSINESS, submitBusinessRequest);
        if(r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())){
            if(r.bizContent != null){
                currentContext.setState(5);
                currentContextService.update(currentContext);
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        }else{
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
            return result;
        }*/
        return result;
    }


    @PostMapping("/cancelBusiness")
    @ApiOperation("业务单取消接口")
    public JSONResult cancelBusiness(@RequestBody CancelBusinessRequest req) {
        JSONResult result = new JSONResult();
        log.info("cancelBusiness:{}", JSON.toJSONString(req));
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("该用户不在申办流程当中！");
        }
        if (currentContext.getState() != 4) {
            result.setCode(JSONResult.FAIL);
            result.setCurrentTime("" + System.currentTimeMillis());
            result.setMessage("订单暂时无法取消！");
        }
        log.info("cancelBusiness-currentContext:{}", JSON.toJSONString(currentContext));

        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        req.setOrderNo(accessno + req.getOrderNo());
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.CANCEL_BUSINESS, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());

                currentContext.setState(1);
                currentContext.setApplyId(null);
                currentContext.setCarId(null);
                currentContext.setJsonData("");
                currentContext.setCsUserNo("");
                currentContextService.update(currentContext);
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/checkVehilce")
    @ApiOperation("车辆卡签校验查询接口(本省)：响应码1007:该车在外省（本省XX机构）发行过卡签\n" +
            "1008:该车在本机构发行过卡\n" +
            "1009:该车在本机构发行过签\n" +
            "1010:该车在本机构发行不存在\n" +
            "1030:该车在本机构发行过卡与签")
    public JSONResult checkVehilce(@RequestBody CheckVehilceRequest req) {
        JSONResult result = new JSONResult();
        log.info("checkVehilce:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.CHECK_VEHILCE, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/checkAndQueryVehilce")
    @ApiOperation("车辆卡签校验查询接口(全国和本省)：" +
            "用户需要先开户才能校验，如果返回车辆信息为空，则只支持车辆信息修改，如果车辆信息不为空，支持新增\n" +
            "1010:该车在本机构发行不存在")
    public JSONResult checkAndQueryVehilce(@RequestBody CheckAndQueryVehilceRequest req) {
        JSONResult result = new JSONResult();
        log.info("checkAndQueryVehilce:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.CHECK_AND_QUERY_VEHILCE, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/getBusinessDetail")
    @ApiOperation("申办订单详情")
    public JSONResult getBusinessDetail(@RequestBody GetBusinessDetailRequest req) {
        JSONResult result = new JSONResult();
        log.info("getBusinessDetail:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.GET_BUSINESS_DETAIL, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/vehOwnAddPic")
    @ApiOperation("车主图片上传")
    public JSONResult vehOwnAddPic(@RequestBody VehOwnAddPicRequest req) {
        JSONResult result = new JSONResult();
        log.info("vehOwnAddPic:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_VEHOWN_ADD_PIC, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/vehOwnUpdate")
    @ApiOperation("车主信息修改")
    public JSONResult vehOwnUpdate(@RequestBody VehOwnUpdateRequest req) {
        JSONResult result = new JSONResult();
        log.info("vehOwnUpdate:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_VEHOWN_UPDATE, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/agentUpdate")
    @ApiOperation("修改经办人信息")
    public JSONResult agentUpdate(@RequestBody UpdateAgentRequest req) {
        JSONResult result = new JSONResult();
        log.info("agentUpdate:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.ISSUE_AGENT_UPDATE, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/queryCustomerInfo")
    @ApiOperation("查询ETC客户信息:如果返回客户信息，只支持用户修改信息，不支持新增,如果用户是单位用户(证件类型5~10)且\n" +
            "接口未返回用户经办人信息，则需录入单位经办人信息")
    public JSONResult queryCustomerInfo(@RequestBody QueryCustomerInfoRequest req) {
        JSONResult result = new JSONResult();
        log.info("queryCustomerInfo:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.QUERY_CUSTOMER_INFO, req);
        JSONObject jsonObject = new JSONObject();
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
            }
        } else if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.USER_EXIST.getCode())) {
            jsonObject.put("state", 0);
            result.setCode(r.getCode());
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
            result.setRspData(JSON.toJSONString(jsonObject));
        } else {
            result.setCode(r.getCode());
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/queryVehilce")
    @ApiOperation("车辆信息查询:如果返回车辆信息为空，则只支持车辆信息修改，如果车辆信息不为空，支持新增")
    public JSONResult queryVehilce(@RequestBody QueryVehilceRequest req) {
        JSONResult result = new JSONResult();
        log.info("queryVehilce:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.QUERY_VEHILCE, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/submitBusiness")
    @ApiOperation("申办订单提交")
    public JSONResult submitBusiness(@RequestBody SubmitBusinessRequest req) {
        JSONResult result = new JSONResult();
        log.info("submitBusiness:{}", JSON.toJSONString(req));
        CurrentContext currentContext = currentContextService.getByUserId(req.getUserId());
        if (currentContext == null) {
            result.setCode(com.czmh.etc.onlinepubsys.json.mingchuang.JSONResult.FAIL);
            result.setMessage("当前用户不在申请流程中");
            return result;
        }
        req.setCsUserNo(currentContext.getCsUserNo());
        //使用车辆信息id作为提交招商局的订单号
        req.setOrderNo(accessno + currentContext.getCarId());
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);

        ApiResponseBase r = CmgHttpUtil.post(BusinessType.SUBMIT_BUSINESS, req);
        //当提交订单返回订单已存在状态码则返回成功标识给前端进行正常激活
        if (r != null && (r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode()) || r.getCode().equalsIgnoreCase("ORDER_IS_EXIST"))) {
            if (r.bizContent != null || r.getCode().equalsIgnoreCase("ORDER_IS_EXIST")) {
                currentContext.setState(4);
                currentContextService.update(currentContext);
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
            return result;
        }
        return result;
    }

    @PostMapping("/updateCustomerInfo")
    @ApiOperation("更新ETC客户信息:个人用户返回用户编号,经办人返回为空字符串")
    public JSONResult updateCustomerInfo(@RequestBody UpdateCustomerInfoRequest req) {
        JSONResult result = new JSONResult();
        log.info("updateCustomerInfo:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.UPDATE_CUSTOMER_INFO, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

    @PostMapping("/updateVehicle")
    @ApiOperation("更新车辆信息")
    public JSONResult updateVehicle(@RequestBody UpdateVehicleRequest req) {
        JSONResult result = new JSONResult();
        log.info("updateVehicle:{}", JSON.toJSONString(req));
        Long time = System.currentTimeMillis();
        req.setClientKey(accessno + time);
        req.setTime(time);
        ApiResponseBase r = CmgHttpUtil.post(BusinessType.UPDATE_VEHICLE, req);
        if (r != null && r.getCode().equalsIgnoreCase(ApiCodeEnum.SUCCESS.getCode())) {
            if (r.bizContent != null) {
                result.setRspData(r.getBizContent());
                result.setMessage(r.getMsg());
                result.setCurrentTime(r.getReceiveTime());
            }
        } else {
            result.setCode(r != null ? r.getCode() : JSONResult.FAIL);
            result.setMessage(r.getMsg());
            result.setCurrentTime(r.getReceiveTime());
        }
        return result;
    }

}
